<template>
  <div class="container">
    <div class="app-container">
      <!-- 左面结构 -->
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin: 10px"
          size="mini"
          placeholder="输入员工名称搜索"
          prefix-icon="el-icon-search"
          @input="changValue"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :data="depts"
          :props="defaultProps"
          highlight-current
          default-expand-all
          :expand-on-click-node="false"
          @current-change="selectNode"
        />
      </div>
      <!-- 右面结构 -->
      <div class="right">
        <el-row class="operate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button
            size="mini"
            @click="showExcelDialog = true"
          >excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" label="头像">
            <template v-slot="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :size="30"
                :src="row.staffPhoto"
              />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span>{{ row.formOfEmployment === 1 ? "正式" : "非正式" }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button
                  slot="reference"
                  style="margin-left: 10px"
                  size="mini"
                  type="text"
                >删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row align="middle" style="height: 60px" type="flex" justify="end">
          <el-pagination
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            layout="total, prev, pager, next"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <!-- 放excel 弹出框 -->
    <!-- .sync语法糖帮我们自动写了 @update:a="a=$event" -->
    <!-- update:props属性名，值 直接修改 .sync修饰符的属性值  -->
    <ImportExcel
      :show-excel-dialog.sync="showExcelDialog"
      @uploadSuccess="getEmployeeList"
    />
    <!-- <ImportExcel :a="a" @update:a="a=$event" /> -->
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="btnRoleOk">确定</el-button>
          <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
// 渲染员工数据
// 1. 封装接口
// 2. 初始化调用接口渲染数据
// 3. 切换树节点 调用接口渲染数据
import { getDepartment } from '@/api/department'
import { getEmployeeList, exportEmployee, delEmployee, getEnableRoleList, assignRole, getEmployeeDetail } from '@/api/employee'
import { transListToTreeData } from '@/utils/index'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      showExcelDialog: false,
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 查询条件可能会有很多参数
      queryParams: {
        departmentId: null,
        page: 1, // 当前页码
        pagesize: 10,
        keyword: '' // 模糊搜索字段
      },
      list: [],
      total: 0, // 员工总数
      timer: null, // 定时器
      showRoleDialog: false, // 角色弹出框控制变量
      roleIds: [],
      roleList: [],
      currentUserId: null // 记录当前点击的用户id
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获取树数据
    async getDepartment() {
      const result = await getDepartment()
      this.depts = transListToTreeData(result, 0)
      this.queryParams.departmentId = this.depts[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完再设置
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    // 获取员工列表方法
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    // 点击树节点方法
    selectNode(node) {
      console.log(node)
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeList()
    },
    // 切换页码
    changePage(newPage) {
      this.queryParams.page = newPage
      this.getEmployeeList() // 查询数据
    },
    // 模糊搜索
    changValue() {
      console.log(this.queryParams.keyword)
      // 防抖
      // 准备定时器 每一次触发 都清理一下上次的定时器
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        // console.log('我执行了')
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 导出excel
    async exportEmployee() {
      const res = await exportEmployee()
      // FileSaver.saveAs(数据流, 名字)
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    // 删除员工
    async confirmDel(id) {
      console.log(id)
      await delEmployee(id)
      // 判断length是不是等于1    页码是不是第一页
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    // 显示角色弹出框
    async btnRole(id) {
      this.currentUserId = id
      this.roleList = await getEnableRoleList()
      const { roleIds } = await getEmployeeDetail(id)
      console.log(roleIds)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async btnRoleOk() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .operate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
